# !/usr/bin/python
# -*- coding: utf-8 -*-
"""
@FileName:  Get_Book_img.py
@Time    :  2022-1-3 19:32
@Author  :  Alan_1999
@Version :  1.0
@License :  (C)Copyright 2021-2022
@Desc    :  获取小说封面图，爬取页面搜索结果  https://www.mx-fm.com/fmsc/
"""
import os

import requests
from lxml import etree


def Save_Img(img_html, count):
    file_addr = r"E:\WorkSpace\PyCharm\Book-Shop\static\images\bk" + str(count) + ".jpg"  # 保存图片到相应路径下
    if os.path.isfile(file_addr):  # 如果已经存在同名文件，则删除
        os.remove(file_addr)
    img = requests.get(img_html)  # 获取源码
    with open(file_addr, "wb") as f:  # 打开文件编辑
        f.write(img.content)
    print(f"{file_addr}已经保存")  # 输出提示信息
    f.close()


def Get_Img():
    count = 1
    index_html = "https://www.mx-fm.com/fmsc/"  # 网站源码
    clas = ["nan", "nv", "nannv", "yishou", "qita"]  # 类别
    start, end = 45100, 45500  # 观察得到部分url信息
    for item in clas:
        for i in range(start, end):
            img_html = f"{index_html}{item}/{i}.html"  # 拼凑得图片网址
            try:  # 尝试爬取，若出现错误则跳过当前图片
                get_res = requests.get(img_html).text
                xml_res = etree.HTML(get_res)
                img = xml_res.xpath('//*[@id="viewer_1"]/li/div')[0].xpath("./img/@src")  # 解析得到图片url
                if len(img):
                    # print(img_html, img)
                    Save_Img(img[0], count)
                    count += 1
                else:
                    print(img, img_html)
            except:  # 提示图片错误信息
                print(f"{img_html}错误！")
                continue
    print(f"共计{count}张图片")


if __name__ == '__main__':
    Get_Img()
